package com.zzptc.shop.db;

import com.zzptc.shop.util.MyUtil;

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Map;

public class MysqlDB implements IDB{
    //全局变量
    private Connection conn;
    private Map map;
    private String DRIVME;
    private String URL;
    private String UNAME;
    private String PWD;
    /*private String URL="jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8";
    private String DRIVME="com.mysql.jdbc.Driver";
    private String UNAME="root";
    private String PWD="root";*/

    @Override
    public Connection getConnection() throws SQLException{
        try {
            map= MyUtil.readXML();
            DRIVME= (String) map.get("driver");
            URL= (String) map.get("url");
            UNAME= (String) map.get("uname");
            PWD= (String) map.get("pwd");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //加载数据库驱动
        try {
            Class.forName(DRIVME);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        //获得数据库连接
        conn=DriverManager.getConnection(URL,UNAME,PWD);
        return conn;
    }

    @Override
    public void closeConn() throws SQLException {
        if(conn!=null&&!conn.isClosed()){
            conn.close();
        }
    }

    public static void main(String[] args) {
        MysqlDB s=new MysqlDB();
        try {
            System.out.println(s.getConnection().isClosed());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
